const {ccclass, property} = cc._decorator;
/**
 * 地图上的物品
 */
@ccclass
export default class mapItem extends cc.Component {
    private itemDat:QM.Item;    
    private _item:Db.Item;
    get item(){
        if(!this._item){
            this._item = Db.getItem(this.itemDat.itemId);
        }
        return this._item;
    }

    private _sprite:cc.Sprite;
    get sprite(){
        if(!this._sprite){
            var sp = this.getComponent(cc.Sprite);
            if(!sp){
                sp = this.addComponent(cc.Sprite);
            }
            this._sprite = sp;
            this._sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
        }
        return this._sprite;
    }

    onLoad(){
        this.node.on(cc.Node.EventType.TOUCH_END,this.touchEnd,this);
    }


    setData(itemDat:QM.Item){
        this.itemDat = itemDat;
        this.show();
    }

    show(){
        this.node.setContentSize(40,40);
        if(this.itemDat.show){
            this.sprite.spriteFrame = cc.loader.getRes("Item/Map/饭菜",cc.SpriteFrame);
        }
    }

    /** 当物品点击后 拾取 */
    touchEnd(){ 
        if(!this.itemDat.isPickUp) return;
        QM.game.updatePackItem({
            itemId:this.item.id,
            cmd:"add"
        });        
        //销毁地图数据
        var mapDat = QM.game.getMapDat();        
        var items = mapDat.item;
        if(items){
            for(let i=0;i<items.length;i++){
                if(items[i].itemId==this.itemDat.itemId){
                    items.splice(i,1);
                    break;
                }
            }
        }

        //播报一个获取物品的提示
        var plot:Db.Plot = {
            class:"dialog",
            type:"aside",
            expand:{
                name:"",
                content:"获得"+this.item.desc
            }
        }

        var event = new cc.Event.EventCustom("GetItemPlot",true);
        event.setUserData([plot]);
        this.node.dispatchEvent(event);

        //销毁地图上的物品
        this.node.destroy();
    }
}
